//
//  HZPopMenuView.m
//  HZTC_YaDeArt
//
//  Created by MayerF on 17/4/5.
//  Copyright © 2017年 HZTC. All rights reserved.
//

#import "HZPopMenuView.h"
#import "MYCommonTool.h"

@implementation HZPopMenuModel
@end

#define kLeftRightMargin 15
#define kNameW 200
@interface HZPopMenuCell()
@property (nonatomic, strong)UILabel *pName;
@property (nonatomic, strong)UIImageView *pImage;
@end
@implementation HZPopMenuCell

+ (HZPopMenuCell *)cellTableView:(UITableView *)tableView
                                 indexPath:(NSIndexPath *)indexPath
                                 cellModel:(HZPopMenuModel *)cellModel
                                 cellHight:(CGFloat)cellHight
{
    return [self leftCellTableView:tableView indexPath:indexPath cellModel:cellModel cellHight:cellHight];
}

+ (HZPopMenuCell *)leftCellTableView:(UITableView *)tableView
                                     indexPath:(NSIndexPath *)indexPath
                                     cellModel:(HZPopMenuModel *)cellModel
                                     cellHight:(CGFloat)cellHight
{
    static NSString *ID = @"popMenuCell";
    HZPopMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[HZPopMenuCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        [cell p_commonInit];
    }
    [cell p_updateDataWithmodel:cellModel indexPath:indexPath cellH:cellHight];
    
    return cell;
}

- (void)p_commonInit
{
    _pName = [UILabel new];
    _pImage = [UIImageView new];
    
    _pImage.hidden = YES;
    
    [self.contentView addSubview:_pName];
    [self.contentView addSubview:_pImage];
    
    [self p_initConstraints];
}

- (void)p_initConstraints
{
    [_pName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self).offset(kLeftRightMargin);
        make.bottom.mas_equalTo(self);
        make.width.mas_equalTo(kNameW);
    }];
    [_pImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.right.mas_equalTo(self).offset(-kLeftRightMargin);
        make.bottom.mas_equalTo(self);
        make.width.mas_equalTo(80);
    }];
    
}

- (void)p_updateDataWithmodel:(HZPopMenuModel *)model indexPath:(NSIndexPath *)indexPath cellH:(CGFloat)cellH
{
    [self p_cleaOldData];
    [self p_updateNewData:model];
}

- (void)p_updateNewData:(HZPopMenuModel *)model
{
    _pName.text = model.model_name;
//    _pImage.hidden = model.isShowImage;
    if (model.isShowImage) {
        self.accessoryType = UITableViewCellAccessoryCheckmark;
        self.tintColor = [UIColor redColor];
    }else {
        self.accessoryType = UITableViewCellAccessoryNone;
    }
}

- (void)p_cleaOldData
{
    [_pName setText:@""];
}

@end

#define kTopBgViewH 45
#import "MYCustomLeftRightBtn.h"

@interface HZPopMenuView()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong)UIView *pTranslucentView;
@property (nonatomic, strong)UIView *pTopBgView;
@property (nonatomic, strong)UITableView *pTableView;
@property (nonatomic, strong)NSArray *pListData;
@property (nonatomic, strong)NSArray *pContentArray;
@property (nonatomic, strong)NSMutableArray *pTitleBtnArray;
@property (nonatomic, assign)NSInteger nCurrentColmn;
@end

@implementation HZPopMenuView

#pragma mark -
#pragma mark 生命周期
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self p_commonInit];
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}
#pragma mark -
#pragma mark public
- (void)setTitleArray:(NSArray *)titleArray
{
    if (titleArray.count == 0) { return;}
    _titleArray = titleArray;

    [self p_dynamicSetTitle:titleArray];
    [self p_updateConstaints];
}

- (void)setContentArray:(NSArray<NSArray<HZPopMenuModel *> *> *)contentArray
{
    if (contentArray.count == 0) { return;}
    _pContentArray = contentArray;
    _pListData = contentArray[0];
    [_pTableView reloadData];
}

- (void)refreshContentData:(NSArray<NSString *> *)contentData index:(NSInteger)index
{
    if (!contentData || contentData.count == 0) { return;}
    if (index > _pContentArray.count - 1) { return;}
    
    NSArray *pIndexContentArray = _pContentArray[index];
    
    if (pIndexContentArray.count <= contentData.count) {
        NSMutableArray *tempSingleContent = [NSMutableArray array];
        for (int i = 0; i < contentData.count; i++) {
            NSString *newTitle = contentData[i];
            if (i <= pIndexContentArray.count - 1) {
                HZPopMenuModel *model = pIndexContentArray[i];
                model.model_name = newTitle;
                [tempSingleContent addObject:model];
            }else {
                HZPopMenuModel *model = [HZPopMenuModel new];
                model.model_name = newTitle;
                [tempSingleContent addObject:model];
            }
        }
        
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:_pContentArray];
        [tempArray replaceObjectAtIndex:index withObject:tempSingleContent];
        _pContentArray = tempArray;
    }else {
        [pIndexContentArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx <= contentData.count - 1) {
                NSString *newTitle = contentData[idx];
                HZPopMenuModel *model = (HZPopMenuModel *)obj;
                model.model_name = newTitle;
            }else {
                *stop = YES;
            }
        }];
    }
}

- (void)resetOrigitState
{
    for (int i = 0; i < _titleArray.count; i++) {
        NSString *title = _titleArray[i];
        UIButton *btn = _pTitleBtnArray[i];
        [btn setTitle:title forState:UIControlStateNormal];
    }
    for (NSArray *content in _pContentArray) {
        [content enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HZPopMenuModel *model = (HZPopMenuModel *)obj;
            if (idx == 0) {
                model.isShowImage = YES;
            }else{
                model.isShowImage = NO;
            }
        }];
    }
}

- (NSArray *)getTitleArray
{
    NSMutableArray *tempArray = [NSMutableArray array];
    for (UIButton *btn in _pTitleBtnArray) {
        [tempArray addObject:btn.currentTitle];
    }
    return tempArray;
}
- (void)updateTitle:(NSString *)title index:(NSInteger)index
{
    UIButton *btn = _pTitleBtnArray[index];
    [btn setTitle:title forState:UIControlStateNormal];
}
#pragma mark -
#pragma mark private
- (void)p_commonInit
{
    _pTranslucentView = [UIView new];
    _pTopBgView = [UIView new];
    _pTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _pTableView.delegate = self;
    _pTableView.dataSource = self;
    
    _pTranslucentView.alpha = 0;
    _pTranslucentView.backgroundColor = kMYHexToRGB(0x808080, 0.5);
    _pTableView.tableFooterView = [UIView new];
    _pTopBgView.backgroundColor = kMYHexToRGB(0xe4e4e4, 1);
    
    [self addSubview:_pTranslucentView];
    [self addSubview:_pTableView];
    [self addSubview:_pTopBgView];
    
    [self p_initConstraints];
    
    _pTitleBtnArray = [NSMutableArray arrayWithCapacity:5];
}

- (void)p_initConstraints
{
    [_pTranslucentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.height.mas_equalTo(kScreenH);
    }];
    [_pTopBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.bottom.mas_equalTo(self);
    }];
    [_pTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.top.mas_equalTo(_pTopBgView.mas_bottom);
        make.height.mas_equalTo(0);
    }];
}

- (void)p_updateConstaints
{
    NSInteger nCounts = _pTitleBtnArray.count;
    if (nCounts == 1) {
        [_pTitleBtnArray[0] mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_pTopBgView);
            make.left.mas_equalTo(_pTopBgView);
            make.right.mas_equalTo(_pTopBgView);
            make.bottom.mas_equalTo(_pTopBgView).offset(-0.5);
        }];
    }else {
        UIButton *preBtn = [_pTitleBtnArray firstObject];
        [preBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(_pTopBgView);
            make.left.mas_equalTo(_pTopBgView);
            make.bottom.mas_equalTo(_pTopBgView).offset(-0.5);
        }];
        for (int i = 1; i < _pTitleBtnArray.count; i++) {
            UIButton *btn = _pTitleBtnArray[i];
            if (i == nCounts - 1) {
                [btn mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.mas_equalTo(_pTopBgView);
                    make.left.mas_equalTo(preBtn.mas_right).offset(0.5);
                    make.bottom.mas_equalTo(_pTopBgView).offset(-0.5);
                    make.width.mas_equalTo(preBtn);
                    make.right.mas_equalTo(_pTopBgView);
                }];
                return;
            }
            [btn mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(_pTopBgView);
                make.left.mas_equalTo(preBtn.mas_right).offset(0.5);
                make.bottom.mas_equalTo(_pTopBgView).offset(-0.5);
                make.width.mas_equalTo(preBtn);
            }];
            
            preBtn = btn;
        }
    }
    
}

- (void)p_addTranslucentView
{
    [self addSubview:_pTranslucentView];
    [self sendSubviewToBack:_pTranslucentView];
    [_pTranslucentView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self);
        make.left.mas_equalTo(self);
        make.right.mas_equalTo(self);
        make.height.mas_equalTo(kScreenH);
    }];
}

- (void)p_animateShowContent:(BOOL)isShow
{
    CGFloat fTableViewH = kTopBgViewH*_pListData.count;
    if (fTableViewH > 360) {
        fTableViewH = 360;
    }
    if (isShow) {
        [_pTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(fTableViewH);
        }];
    }else {
        [_pTableView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
    }

    [self setNeedsUpdateConstraints];
    [self updateConstraintsIfNeeded];
    [_pTopBgView layoutIfNeeded];
    [UIView animateWithDuration:0.2 animations:^{
        [self layoutIfNeeded];
    }];
}

- (void)p_animateShowBgView:(BOOL)isShow
{
    if (isShow) {
        [self p_addTranslucentView];
        [UIView animateWithDuration:0.2 animations:^{
            _pTranslucentView.alpha = 0.6f;
        }];
    }else {
        [UIView animateWithDuration:0.2 animations:^{
            _pTranslucentView.alpha = 0.f;
        } completion:^(BOOL finished) {
            [_pTranslucentView removeFromSuperview];
        }];
    }
}

- (void)p_showMenu:(BOOL)isShow
{
    [self.superview bringSubviewToFront:self];
    [self p_animateShowBgView:isShow];
    [self p_animateShowContent:isShow];
}

- (void)p_clickListData:(NSIndexPath *)indexPath
{
    HZPopMenuModel *model = _pListData[indexPath.row];
    UIButton *currentBtn = _pTitleBtnArray[_nCurrentColmn];
    NSString *tempStr = model.model_name;
    if ([model.model_name isEqualToString:@"全部"]) {
        tempStr = _titleArray[_nCurrentColmn];
    }
    [currentBtn setTitle:tempStr forState:UIControlStateNormal];
    
    for (HZPopMenuModel *model in _pListData) {
        model.isShowImage = NO;
    }
    model.isShowImage = YES;
    
    [self p_showMenu:NO];
    for (UIButton *otherBtn in _pTitleBtnArray) {
        otherBtn.selected = NO;
    }
}

- (NSArray *)p_packParams
{
    NSMutableArray *pTempArray = [NSMutableArray arrayWithCapacity:5];
    for (UIButton *btn in _pTitleBtnArray) {
        [pTempArray addObject:btn.currentTitle];
    }
    
    return pTempArray;
}
#pragma mark -
#pragma mark action
- (void)titleBtnOnClick:(UIButton *)btn
{
    _nCurrentColmn = btn.tag;
    _pListData = _pContentArray[btn.tag];
    [_pTableView reloadData];
    btn.selected = !btn.selected;
    [self p_showMenu:btn.selected];
    [_pTableView reloadData];
    
    for (UIButton *otherBtn in _pTitleBtnArray) {
        if (![otherBtn isEqual:btn]) {
            otherBtn.selected = NO;
        }
    }
}

- (void)p_dynamicSetTitle:(NSArray *)titleArray
{
    for (int i = 0; i < titleArray.count; i++) {
        NSString *title = titleArray[i];
        UIButton *btn = [MYCustomLeftRightBtn new];
        btn.tag = i;
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"mark_down"] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(titleBtnOnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        btn.titleLabel.adjustsFontSizeToFitWidth = YES;
        [_pTopBgView addSubview:btn];
        [_pTitleBtnArray addObject:btn];
    }
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _pListData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row > _pListData.count - 1) { return nil;}
    HZPopMenuModel *mode = _pListData[indexPath.row];
    HZPopMenuCell *cell = [HZPopMenuCell leftCellTableView:tableView indexPath:indexPath cellModel:mode cellHight:0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
#pragma mark -
#pragma mark UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kTopBgViewH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self p_clickListData:indexPath];
    if ([self.delegate respondsToSelector:@selector(popMenuViewDidSelectedRowWithContent:)]) {
        [self.delegate popMenuViewDidSelectedRowWithContent:[self p_packParams]];
    }
}
#pragma mark -
#pragma mark event
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        for (UIView *subView in self.subviews) {
            CGPoint tp = [subView convertPoint:point fromView:self];
            if (CGRectContainsPoint(subView.bounds, tp)) {
                view = subView;
            }
        }
    }
    return view;
}
@end
